﻿using System.IO;

namespace Z.IconLibraryGenerator.WinForm
{
    public partial class IconLibraryGeneratorManager
    {
        public static void GenerateProjectIconFile(ProjectConfiguration project)
        {
            var dir = My.TemplateFile.ProjectIconFile;
            var dirOutput = Path.Combine(project.OutputDirectory, project.ProjectName);

            var isLegacy = project.Framework == ProjectFrameworkType.Framework20;

            foreach (var icon in project.Icons)
            {
                string frameworkVersion = isLegacy ? "v2.0" : "v3.5";
                string namespaceStart = isLegacy ? "namespace " + project.ProjectNamespace + "{" : "";
                string namespaceEnd = isLegacy ? "}" : "";
                string CssFileName = "";
                string HandlerPath = project.ProjectNamespace + ".axd";

                foreach (var file in dir.GetFiles("*.*", SearchOption.AllDirectories))
                {
                    var template = file.ReadToEnd();

                    template = template.Replace("@(Model.ProjectName)", project.ProjectName);
                    template = template.Replace("@(Model.Namespace)", project.ProjectNamespace);
                    template = template.Replace("@(Model.HandlerPath)", HandlerPath);
                    template = template.Replace("@(Model.CssFileName)", CssFileName);
                    template = template.Replace("@(Model.CssFileNameDebug)", CssFileName.Replace(".css", ".debug.css"));
                    template = template.Replace("@(Model.FrameworkVersion)", frameworkVersion);
                    template = template.Replace("@(Model.NamespaceStart)", namespaceStart);
                    template = template.Replace("@(Model.NamespaceEnd)", namespaceEnd);
                    template = template.Replace("@(Model.ExtensionMethod)", isLegacy? "" : "this ");
                    template = template.Replace("@(Model.DestinationName)", icon.Prefix);
                    template = template.Replace("@(Model.Suffix)", "");

                    var newFileName = file.FullName.Replace("@(Model.Namespace)", project.ProjectNamespace);
                    newFileName = newFileName.Replace("@(Model.DestinationName)", icon.Prefix);

                    var output = newFileName.Replace(dir.FullName, dirOutput).ToFileInfo();
                    output = Path.Combine(output.Directory.FullName, output.GetFileNameWithoutExtension()).ToFileInfo();
                    Directory.CreateDirectory(output.Directory.FullName);
                    template.SaveAs(output);
                }
            }
        }
    }
}